package com.liuya.safe.policy.handler;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import com.liuya.common.exception.EntityExistException;
import com.liuya.db.sql.Query;
import com.liuya.db.sql.QueryFactory;
import com.liuya.db.sql.UserValue;
import com.liuya.db.sql.Value;
import com.liuya.db.sql.xml.QueryType;
import com.liuya.entitle.QueryResult;
import com.liuya.safe.model.SafeUser;
import com.liuya.safe.policy.service.QueryManagerService;
import com.liuya.safe.util.AuthUtil;

//@Component("queryTestHandler")
public class QueryTestHandler implements java.io.Serializable {

    private final QueryType xmlQuery;
    private final Query sqlQuery;

    public QueryTestHandler(QueryType xmlQuery) {
        this.xmlQuery = xmlQuery;
        this.sqlQuery = QueryFactory.getQuery(xmlQuery);
    }

    public QueryType getQuery() {
        return xmlQuery;
    }

    public String getSql() {
        return sqlQuery.toSQL();
    }

    public boolean isTestUserNeeded() {
        ArrayList values = sqlQuery.getValues();
        for (Iterator iter = values.iterator(); iter.hasNext();) {
            Value v = (Value) iter.next();

            if (v instanceof UserValue) {
                return true;
            }
        }

        return false;
    }

    public String[] getTestContextFields() {
        ArrayList values = sqlQuery.getValues();
        ArrayList result = new ArrayList(values.size());
        AuthUtil.extractContextValueFields(sqlQuery, result);

        return (String[]) result.toArray(new String[0]);
    }

    public QueryResult run(SafeUser testUser, Map testCtx, int first, int max) {
        return sqlQuery.execute(testUser, testCtx, first, max);
    }

    public String getManagePage() {
//        return "./queryMng.rls";
        return "";
    }

    public void save(String id, QueryManagerService queryManager) throws EntityExistException {
        queryManager.updateQuery(id, (com.liuya.db.sql.xml.Query) xmlQuery);
    }
}
